// components/address/address.js
import province_list from '../../utils/area';
import Dialog from '@vant/weapp/dialog/dialog';
const { reg }=require('../../utils/util');
Component({
  options: {
    addGlobalClass: true,
  },
  /**
   * 组件的属性列表
   */
  properties: {
    i:{
      type:String
    },
    addressDetail:{
      type:Object
    },
    cancel:{
      type:Boolean
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    IDCardUpload:true, //用户是否上传过身份证
    addressInfo:{  //表单信息
      username:"",
      telphone:"",
      address:"",
      detailAddress:"",
      IDcardName:"",
      IDNum:"",
      defaultAddress:false,
    },
    show:false, //地址弹层
    showUpload:false, //身份证弹层
    areaList:province_list,
    autosize:{ minHeight: 60},
    submit:false,
    showCancel:false,
    navigate:false,
    // i:null,//用于判断是否为修改地址时跳转过来
    fileList:[],
    IDcard1:'/images/card_img01.jpg',
    IDcard2:'/images/card_img02.jpg',
  },

  /**
   * 组件的方法列表
   */
  methods: {
    //三级联动收货地址弹层
  onChangeShow(e){
    this.setData({
      show:!this.data.show
    })
  },
  //点击弹层的取消按钮
  onClose(){
    this.setData({
      show:false
    })
  },

  //三级联动收货地址的获取以及绑定
  showData(e){
    const address=e.detail.values;
    let str='';
    address.map(item=>{
      str+=item.name;
    })
    this.setData({
      'addressInfo.address':str,
      show:!this.data.show
    })
  },
 //设置表单中对应的某一个属性的值
  onChangeAddress(e){
    const attr=e.currentTarget.dataset.info;
    const value=e.detail;
    const temp=`addressInfo.${attr}`
    this.setData({
      [temp]:value
    })
  },

  //设置默认收货地址的开关状态
  onChangeSwitch(){
    this.setData({
      'addressInfo.defaultAddress':!this.data.addressInfo.defaultAddress
    })
  },

  //点击提交
  submitAddressInfo(){
    this.setData({
      submit:true
    })
    const {username,telphone,address, detailAddress,defaultAddress}=this.data.addressInfo;
    //判断用户是否将当前地址设置为默认地址,如果是,则获取所有地址列表,将其他的地址的默认属性全修改为false
    if(defaultAddress){
      //获取全部地址列表
      const addressList=[];
      addressList.map(item=>{
        if(item.defaultAddress){
          item.defaultAddress=false
        }
      })
      //发送请求将地址列表更新
    }
    //将必填项解构出并赋值给一个新的对象，用于判断必填项是否填写
    const obj={
      username,
      telphone,
      address,
      detailAddress,
    };
    let flag=true;
    for(let i in obj){
      if(!obj[i]){
        flag=false;
      }
    }
    const addressInfo=JSON.stringify(this.data.addressInfo)
    if(flag && reg.test(obj.telphone)){
      //验证通过则发起请求，并跳转
      //i存在时，是在编辑已有的地址
      if(this.data.i){
        wx.navigateTo({
          url: '/pages/address/index?address='+addressInfo+'&index='+this.data.i,
        })
      }else{
        //i 不存在为新增地址
        wx.navigateTo({
          url: '/pages/address/index?address='+addressInfo,
        })
        this.setData({
          addressInfo:{  //表单信息
            username:"",
            telphone:"",
            address:"",
            detailAddress:"",
            IDcardName:"",
            IDNum:"",
            defaultAddress:false,
          }
        })
      }
    }else if(flag && !reg.test(obj.telphone)){
      Dialog.alert({
        context: this,
        title: '提示',
        message: '请填写正确的手机号码！',
      })
    }else{
      Dialog.alert({
        context: this,
        title: '提示',
        message: '请将信息填写完整！',
      })
    }
  },

  //点击删除
  onRemoveAddress(){
    Dialog.confirm({
      context: this,
      message: '确认要删除改收货地址吗？',
    })
      .then(() => {
        // on confirm
        wx.navigateTo({
          url: '/pages/address/index?remove=1&index='+this.data.i,
        })
      })
  },
  //点击取消
  onHidePage(){
    this.triggerEvent('onHide')
  },

  //身份证上传弹窗
  onIDcardUpload(){
    this.setData({
      showUpload:true
    })
  },
  //身份证上传
  afterRead(event) {
    const { file } = event.detail;
    const { i }=event.currentTarget.dataset; //i为1则为人像面，为2则为国徽面 
    console.log(event.detail);
    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    let that=this;
    wx.uploadFile({
      url:"",
      method:'POST',
      // header: {"Authorization":"Bearer "+app.globalData.token},
      filePath: file.url,
      name: 'file',
      formData: { user: 'test' },
      success(res) {
        console.log(res);
        var result=JSON.parse(res.data);
        // 上传完成需要更新 fileList
        const { fileList = [] } = that.data;
        fileList.push({ ...file, url: result.data });
        that.setData({ fileList });
        if(i=='1'){
          that.setData({ IDcard1:result.data });
        }else if(i=='2'){
          that.setData({ IDcard2:result.data });
        }
      },
    })
  },
//点击上传
    onUpload(){
      this.setData({
        showUpload:false
      })
    },
  },
  
  //组件所在页面的生命周期
  pageLifetimes: {
    show: function() {
      // 页面被展示
      if(this.data.i){
        this.setData({
          addressInfo:this.data.addressDetail,
          navigate:true,
        })
      }
    },
  },
  //小程序组件生命周期
  lifetimes: {
    attached: function() {
      if(this.data.cancel){
        this.setData({
          showCancel:true
        })
      }
    },
  }
})
